#ifndef INCLUDE_EVBS_DISCOVERY_MONITORING_MONITORPID_HPP_
#define INCLUDE_EVBS_DISCOVERY_MONITORING_MONITORPID_HPP_

#include <atomic>
#include <thread>
#include <unordered_map>
#include <vector>
#include <mutex>
#include <functional>
#include <string>
#include <set>
#include <map>

#include <edds/rtps/common/Guid.h>
#include <elog/Log.hpp>

namespace evbs {
namespace ertps {
namespace rtps {

class ProcessExitMonitor {
 private:
    int nl_sock_ = -1;
    std::atomic<bool> running_ {false};
    std::thread monitor_thread_;
    // Map PID to GUID list
    std::unordered_map<int, std::vector<GUID_t>> monitored_pids_;
    mutable std::mutex pids_mutex_;

    std::function<void(int pid, const GUID_t& guid)> exit_callback_;

    // statistics variables
    bool enable_detailed_logging_ = false;
    std::atomic<int> total_events_ {0};
    std::atomic<int> dropped_events_ {0};
    std::atomic<int> monitored_exits_ {0};
    std::atomic<int> non_monitored_exits_ {0};
    std::map<std::string, int> non_monitored_processes_;
    std::map<int, int> non_monitored_exit_codes_;
    std::map<int, int> non_monitored_signals_;
    mutable std::mutex stats_mutex_;

    // Private methods
    void run();
    std::string get_process_name(int pid) const;

    // Static helper method
    static const std::map<int, std::string>& get_signal_names();
    static void signal_handler(int sig) {}

 public:
    ProcessExitMonitor();
    ~ProcessExitMonitor();

    void set_exit_callback(std::function<void(int pid, const GUID_t& guids)> callback = nullptr);

    bool init();
    void start_monitoring();
    void stop();

    // Add PID and corresponding GUID
    void add_pid(int pid, const GUID_t& guid);
    void remove_pid_guid(int pid, const GUID_t& guid);
    void remove_pid(int pid);

    // Static utility methods
    static std::string get_signal_name(int signal_num);
    static std::string analyze_exit_reason(int exit_code, int exit_signal);

    // Debug methods
    void dump_monitored_pids() const;
    static std::string get_process_status(int pid);

    // real-time monitoring method
    void enable_detailed_logging(bool enable = true);
    bool is_enable_detailed_logging() const;
};

}  // namespace rtps
}  // namespace ertps
}  // namespace evbs

#endif  // INCLUDE_EVBS_DISCOVERY_MONITORING_MONITORPID_HPP_